package threading;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-08-03
 * Time: 8:36
 */

//饿汉
class Singleton1 {
    private static Singleton1 instance1 = new Singleton1();

    //获取对象
    public static Singleton1 getInstance1() {
        return instance1;
    }

    //构造方法
    private Singleton1() {

    };
}

//多线程下线程安全饿汉模式
class Singleton2 {

   volatile private static Singleton2 instance2 = null;

    //获取对象
    public static Singleton2 getInstance2() {
        if(instance2 == null) {
            synchronized (Singleton2.class) {
                if(instance2 == null) {
                    instance2 = new Singleton2();
                }
            }
        }
        return instance2;
    }

    //构造方法
    private Singleton2() {

    };
}
public class Test2 {
    public static void main(String[] args) {
        Singleton1 s1 = Singleton1.getInstance1();
        Singleton1 s2 = Singleton1.getInstance1();
        System.out.println(s1 == s2);

        Singleton2 s3 = Singleton2.getInstance2();
        Singleton2 s4 = Singleton2.getInstance2();
        System.out.println(s3 == s4);
    }
}
